@andy.ian/dsh-homing 2.1.13 → 2.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -32,6 +32,8 @@ import { createRestartPolicy } from './restart/face.mjs';
32
32
  import { renderTermPage } from './lib/term-page.mjs';
33
33
  import * as compress from './lib/compress.mjs';
34
34
  import * as office from './lib/office.mjs';
35
+ import * as markdown from './lib/markdown.mjs';
36
+ import { NAV_CSS, topNav } from './lib/nav.mjs';
35
37
  import * as windowRemote from './lib/window-remote.mjs';
36
38
  import { setOrientation, ensureLandscape } from './lib/orientation.mjs';
37
39
  import { protectSecret, unprotectSecret } from './lib/secret.mjs';
@@ -845,11 +847,12 @@ function renderRestartPage({ status, sessions, message, confirmForce, portState
845
847
 
846
848
  const policy = restartPolicy.status()
847
849
  const cfg = policy?.config ?? {}
848
- const nav = '<div class="nav"><a href="/">← 返回 DSH</a><a href="/files">文件</a><a href="/git">Git</a><a href="/term">终端</a><a href="/debug">调试</a></div>'
850
+ const nav = topNav()
849
851
 
850
852
  return '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">'
851
853
  + '<meta name="viewport" content="width=device-width,initial-scale=1">'
852
854
  + '<title>重启 DSH</title><style>'
855
+ + NAV_CSS
853
856
  + 'body{background:#12161d;color:#dbe2ea;font:14px/1.45 system-ui,-apple-system,"Noto Sans SC",sans-serif;margin:0 auto;padding:10px 12px 20px;max-width:620px}'
854
857
  + 'h1{font-size:17px;margin:0}.sub{color:#8b93a1;font-size:12px;margin:2px 0 8px}'
855
858
  + '.nav{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 10px}'
@@ -915,7 +918,7 @@ const DEBUG_HTML = `<!doctype html>
915
918
  <html lang="zh-CN"><head><meta charset="utf-8">
916
919
  <meta name="viewport" content="width=device-width, initial-scale=1">
917
920
  <title>调试 · DSH 手机入口</title>
918
- <style>
921
+ <style>${NAV_CSS}
919
922
  :root { color-scheme: dark; }
920
923
  body { margin:0; font-family: system-ui, -apple-system, "Noto Sans SC", sans-serif; background:#0f1115; color:#e8eaed; }
921
924
  .wrap { max-width: 620px; margin: 0 auto; padding: 20px 16px 60px; }
@@ -941,7 +944,7 @@ const DEBUG_HTML = `<!doctype html>
941
944
  .shots img { width:88px; height:88px; object-fit:cover; border-radius:8px; border:1px solid #262b36; }
942
945
  code { background:#1d2229; padding:1px 5px; border-radius:4px; font-size:12px; }
943
946
  </style></head>
944
- <body><div class="wrap">
947
+ <body><div class="wrap">${topNav({ current: '/debug' })}
945
948
  <h1>调试页</h1>
946
949
  <p class="sub">这一页不依赖移动端样式,界面被改坏时也能打开。</p>
947
950
  <p class="sub"><a href="/">← 返回 DSH</a> · <a href="/term">终端</a> · <a href="/files">文件</a> · <a href="/git">Git</a></p>
@@ -1042,7 +1045,7 @@ const ACCOUNT_HTML = `<!doctype html>
1042
1045
  <html lang="zh-CN"><head><meta charset="utf-8">
1043
1046
  <meta name="viewport" content="width=device-width, initial-scale=1">
1044
1047
  <title>账户 · DSH 手机入口</title>
1045
- <style>
1048
+ <style>${NAV_CSS}
1046
1049
  :root { color-scheme: dark; }
1047
1050
  body { margin:0; font-family: system-ui, -apple-system, "Noto Sans SC", sans-serif; background:#0f1115; color:#e8eaed; }
1048
1051
  .wrap { max-width: 640px; margin: 0 auto; padding: 24px 18px 48px; }
@@ -1059,7 +1062,7 @@ const ACCOUNT_HTML = `<!doctype html>
1059
1062
  ul { padding-left:18px; margin:8px 0 0; font-size:13px; color:#9aa4b2; }
1060
1063
  a { color:#7aa7ff; }
1061
1064
  </style></head>
1062
- <body><div class="wrap">
1065
+ <body><div class="wrap">${topNav({ current: '/dsh_homing/account' })}
1063
1066
  <h1>账户设置</h1>
1064
1067
  <p class="sub"><a href="/dsh_homing/devices">设备管理(吊销/删除已配对设备)→</a></p>
1065
1068
  <p class="sub"><a href="/">← 返回 DSH</a> · <a href="/term">终端</a> · <a href="/files">文件</a> · <a href="/git">Git</a></p>
@@ -1317,7 +1320,7 @@ const LOGIN_HTML = `<!doctype html>
1317
1320
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
1318
1321
  <meta name="robots" content="noindex, nofollow">
1319
1322
  <title>登录 · DSH</title>
1320
- <style>
1323
+ <style>${NAV_CSS}
1321
1324
  :root { color-scheme: dark; }
1322
1325
  * { box-sizing: border-box; }
1323
1326
  body { margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center;
@@ -1337,7 +1340,7 @@ const LOGIN_HTML = `<!doctype html>
1337
1340
  border: 1px solid rgba(255,80,80,.35); color: #ff9b9b; font-size: 13px; }
1338
1341
  .hint { margin-top: 18px; color: #6b7383; font-size: 12px; text-align: center; }
1339
1342
  </style></head>
1340
- <body><div class="card">
1343
+ <body><div class="card">${topNav()}
1341
1344
  <h1>DeepSeek Harness</h1>
1342
1345
  <p class="sub">请输入本机设置的账号密码</p>
1343
1346
  <form method="post" action="/login">
@@ -1356,7 +1359,7 @@ const RESET_HTML = `<!doctype html>
1356
1359
  <html lang="zh-CN"><head><meta charset="utf-8">
1357
1360
  <meta name="viewport" content="width=device-width, initial-scale=1">
1358
1361
  <title>重置密码 · DSH 手机入口</title>
1359
- <style>
1362
+ <style>${NAV_CSS}
1360
1363
  :root { color-scheme: dark; }
1361
1364
  body { margin:0; font-family: system-ui, -apple-system, "Noto Sans SC", sans-serif; background:#0f1115; color:#e8eaed; }
1362
1365
  .wrap { max-width: 460px; margin: 0 auto; padding: 32px 18px; }
@@ -1369,7 +1372,7 @@ const RESET_HTML = `<!doctype html>
1369
1372
  .msg { background:#2a2618; border:1px solid #514a2a; color:#e8d99a; padding:10px 12px; border-radius:9px; margin:12px 0 0; font-size:14px; }
1370
1373
  a { color:#7aa7ff; }
1371
1374
  </style></head>
1372
- <body><div class="wrap">
1375
+ <body><div class="wrap">${topNav()}
1373
1376
  <h1>重置密码</h1>
1374
1377
  <p>重置需要在<strong>运行 DSH 的那台电脑</strong>上取一个重置码——这确保只有能碰到这台机器的人才能重置。</p>
1375
1378
  {{message}}
@@ -2869,7 +2872,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2869
2872
  return;
2870
2873
  }
2871
2874
 
2872
- if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/pdf' || url.pathname === '/files/download' || url.pathname === '/files/compress' || url.pathname === '/files/run'
2875
+ if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/pdf' || url.pathname === '/files/download' || url.pathname === '/files/raw' || url.pathname === '/files/compress' || url.pathname === '/files/run'
2873
2876
  || url.pathname === '/files/rename'
2874
2877
  || url.pathname === '/files/delete' || url.pathname === '/files/paste'
2875
2878
  || url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') {
@@ -2978,6 +2981,42 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2978
2981
  return;
2979
2982
  }
2980
2983
 
2984
+ // Markdown 图片:只允许常见图片格式,内联返回(不下载)
2985
+ if (url.pathname === '/files/raw' && req.method === 'GET') {
2986
+ const target = filebrowse.resolvePath(url.searchParams.get('path') ?? '');
2987
+ const typeByExt = {
2988
+ '.png': 'image/png',
2989
+ '.jpg': 'image/jpeg',
2990
+ '.jpeg': 'image/jpeg',
2991
+ '.gif': 'image/gif',
2992
+ '.webp': 'image/webp',
2993
+ '.bmp': 'image/bmp',
2994
+ };
2995
+ const ext = path.extname(target).toLowerCase();
2996
+ const contentType = typeByExt[ext];
2997
+ if (contentType === undefined) {
2998
+ res.writeHead(415, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
2999
+ res.end('不支持的图片格式\n');
3000
+ return;
3001
+ }
3002
+ let stat = null;
3003
+ try { stat = fs.statSync(target); } catch { stat = null; }
3004
+ if (!stat || !stat.isFile() || stat.size > 20 * 1024 * 1024) {
3005
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
3006
+ res.end('图片不存在或过大\n');
3007
+ return;
3008
+ }
3009
+ appendAudit(dir, 'file-image', { path: target, bytes: stat.size });
3010
+ res.writeHead(200, {
3011
+ 'content-type': contentType,
3012
+ 'content-length': String(stat.size),
3013
+ 'cache-control': 'no-store',
3014
+ 'x-content-type-options': 'nosniff',
3015
+ });
3016
+ fs.createReadStream(target).pipe(res);
3017
+ return;
3018
+ }
3019
+
2981
3020
  // PDF / Office 在线预览:PDF 直接流式返回;Office 先转 PDF(带缓存)
2982
3021
  if (url.pathname === '/files/pdf' && req.method === 'GET') {
2983
3022
  const target = filebrowse.resolvePath(url.searchParams.get('path') ?? '');
@@ -3025,6 +3064,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3025
3064
  res.end(`<!doctype html><meta charset="utf-8"><title>预览失败</title><body style="background:#161a20;color:#e6e8ee;font-family:system-ui;padding:24px">
3026
3065
  <h1 style="font-size:18px">预览失败</h1>
3027
3066
  <p style="color:#9aa3b2">${escapeHtml(String(result.error ?? '未知原因'))}</p>
3067
+ <p><a style="color:#8ab4f8" href="/">← 返回 DSH</a> · <a style="color:#8ab4f8" href="/files?path=${encodeURIComponent(path.dirname(target))}">← 返回文件列表</a></p>
3028
3068
  <p><a style="color:#8ab4f8" href="/files/download?path=${encodeURIComponent(target)}">下载后用 WPS / Office 打开</a></p>
3029
3069
  </body>`);
3030
3070
  return;
@@ -3041,6 +3081,21 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3041
3081
  return;
3042
3082
  }
3043
3083
  const info = filebrowse.readTextFile(asked);
3084
+ const raw = url.searchParams.get('raw') === '1';
3085
+ if (!raw && info.text !== undefined && markdown.isMarkdownFile(info.path)) {
3086
+ // Markdown:服务端渲染成安全 HTML;相对图片走 /files/raw,相对文件链接走文件页
3087
+ const baseDir = path.dirname(info.path);
3088
+ const rendered = markdown.renderMarkdown(info.text, {
3089
+ resolvePath: (relative) => path.resolve(baseDir, relative),
3090
+ imageHref: (absPath) => '/files/raw?path=' + encodeURIComponent(absPath),
3091
+ fileHref: (absPath) => (markdown.isMarkdownFile(absPath)
3092
+ ? '/files/view?path=' + encodeURIComponent(absPath)
3093
+ : '/files/download?path=' + encodeURIComponent(absPath)),
3094
+ });
3095
+ appendAudit(dir, 'file-view', { path: info.path, kind: 'markdown' });
3096
+ sendHtml(renderFileView({ info, rendered }));
3097
+ return;
3098
+ }
3044
3099
  appendAudit(dir, 'file-view', { path: info.path });
3045
3100
  sendHtml(renderFileView({ info }));
3046
3101
  return;
@@ -3321,7 +3376,7 @@ button.danger{background:#3a2226;border-color:#54303a;color:#f0b6bf}
3321
3376
  a{color:#8ab4f8}
3322
3377
  </style>
3323
3378
  <h1>设备管理</h1>
3324
- <p class="sub"><a href="/dsh_homing/account">← 返回账户设置</a></p>
3379
+ <p class="sub"><a href="/">← 返回 DSH</a> · <a href="/dsh_homing/account">← 返回账户设置</a></p>
3325
3380
  <p class="sub">每台配对过的手机/浏览器各占一条。吊销后它的下一次请求立即失效,不用改密码、不用重启。</p>
3326
3381
  ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3327
3382
  <table><thead><tr><th>设备</th><th>最后活跃</th><th>配对日期</th><th></th></tr></thead>
@@ -3,6 +3,8 @@
3
3
  * 全部服务端渲染 + 原生表单:微信/鸿蒙浏览器里最稳,不依赖任何 JS 框架。
4
4
  */
5
5
 
6
+ import { NAV_CSS, topNav } from './nav.mjs'
7
+
6
8
  const escapeHtml = (value) => String(value ?? '')
7
9
  .replaceAll('&', '&amp;')
8
10
  .replaceAll('<', '&lt;')
@@ -37,14 +39,38 @@ const STYLE = `
37
39
  .chip { background:#1b2030; border:1px solid #2a3550; color:#9fc0ff; border-radius:999px; padding:6px 12px; font-size:12px; }
38
40
  .crumb { color:#8ab4f8; }
39
41
  .kbd { font-family: ui-monospace, Menlo, Consolas, monospace; background:#1d2229; padding:1px 5px; border-radius:4px; font-size:12px; }
42
+ .md-body { font-size:14px; line-height:1.7; color:#dfe6ef; word-break:break-word; }
43
+ .md-body > :first-child { margin-top:0; }
44
+ .md-body h1, .md-body h2, .md-body h3, .md-body h4, .md-body h5, .md-body h6 { line-height:1.35; margin:20px 0 10px; color:#f2f5f9; }
45
+ .md-body h1 { font-size:22px; border-bottom:1px solid #262b35; padding-bottom:8px; }
46
+ .md-body h2 { font-size:19px; border-bottom:1px solid #1d222b; padding-bottom:6px; }
47
+ .md-body h3 { font-size:17px; }
48
+ .md-body h4 { font-size:15px; }
49
+ .md-body p { margin:10px 0; }
50
+ .md-body ul, .md-body ol { padding-left:22px; margin:10px 0; }
51
+ .md-body li { margin:4px 0; }
52
+ .md-body li > ul, .md-body li > ol { margin:4px 0; }
53
+ .md-body code { font-family: ui-monospace, Menlo, Consolas, monospace; background:#1b2028; border:1px solid #262d38; border-radius:5px; padding:1px 5px; font-size:12.5px; }
54
+ .md-body pre { background:#12151b; border:1px solid #21262f; border-radius:10px; padding:12px; overflow:auto; margin:12px 0; }
55
+ .md-body pre code { background:none; border:0; padding:0; font-size:12.5px; }
56
+ .md-body blockquote { margin:12px 0; padding:8px 12px; border-left:3px solid #3f5f9c; background:#151a22; color:#b9c3d1; border-radius:0 8px 8px 0; }
57
+ .md-body blockquote p { margin:4px 0; }
58
+ .md-body table { width:100%; border-collapse:collapse; margin:12px 0; font-size:13px; }
59
+ .md-body th, .md-body td { padding:8px 10px; border:1px solid #262d38; text-align:left; vertical-align:top; }
60
+ .md-body th { background:#1b2028; color:#cfd8e3; }
61
+ .md-body hr { border:0; border-top:1px solid #262b35; margin:18px 0; }
62
+ .md-body img { max-width:100%; height:auto; border-radius:8px; }
63
+ .md-body a { color:#8ab4f8; text-decoration:none; border-bottom:1px solid rgba(138,180,248,.35); }
64
+ .md-body input[type=checkbox] { margin:0 4px 0 0; vertical-align:middle; }
65
+ .md-body a.md-img { border-bottom:0; }
40
66
  `
41
67
 
42
- export function layout({ title, body }) {
68
+ export function layout({ title, body, current = '/files' }) {
43
69
  return `<!doctype html>
44
70
  <html lang="zh-CN"><head><meta charset="utf-8">
45
71
  <meta name="viewport" content="width=device-width, initial-scale=1">
46
72
  <title>${escapeHtml(title)} · DSH 文件</title>
47
- <style>${STYLE}.flist { display: flex; flex-direction: column; }
73
+ <style>${STYLE}${NAV_CSS}.flist { display: flex; flex-direction: column; }
48
74
  .sortbar { display: flex; align-items: center; gap: 6px; padding: 6px 2px 8px; color: #8b93a1; font-size: 12px; }
49
75
  .sortlabel { margin-right: 2px; }
50
76
  .sortbtn { padding: 4px 9px; border-radius: 6px; background: #222833; border: 1px solid #333c48; color: #b9c3d1; font-size: 12px; }
@@ -59,7 +85,7 @@ export function layout({ title, body }) {
59
85
  .fempty { padding: 18px 4px; color: #8b93a1; }
60
86
  .flist .mm { grid-area: menu; }
61
87
  </style></head>
62
- <body><div class="wrap">${body}</div></body></html>`
88
+ <body><div class="wrap">${topNav({ current })}${body}</div></body></html>`
63
89
  }
64
90
 
65
91
  const messageHtml = (message, isError) => (message
@@ -292,11 +318,6 @@ ${entry.dir ? `<a class="mi" role="menuitem" data-act="paste" data-path="${escap
292
318
  <div style="display:flex;align-items:center;gap:8px;flex-wrap:nowrap;min-width:0">
293
319
  <h1 style="margin:0;flex:0 0 auto;font-size:18px">文件</h1>
294
320
  <div style="flex:1 1 auto;display:flex;align-items:center;justify-content:flex-end;gap:4px;flex-wrap:nowrap;overflow-x:auto;-webkit-overflow-scrolling:touch;scrollbar-width:none">
295
- <a class="btn ghost" href="/" style="${navStyle}">DSH</a>
296
- <a class="btn ghost" href="/term" style="${navStyle}">终端</a>
297
- <a class="btn ghost" href="/remote" style="${navStyle}">窗口</a>
298
- <a class="btn ghost" href="/vnc" style="${navStyle}">桌面</a>
299
- <a class="btn ghost" href="/git?path=${encodeURIComponent(info.path)}" style="${navStyle}">Git</a>
300
321
  <a class="btn ghost" href="/files?path=${encodeURIComponent(home)}" style="${navStyle}">HOME</a>
301
322
  <a class="btn ghost" href="/files?path=${encodeURIComponent(dataDir)}" style="${navStyle}">配置</a>
302
323
  ${parent}
@@ -401,16 +422,25 @@ export function renderCompressPage({ target, archive, message, isError, done = f
401
422
  return layout({ title: '加密压缩 · ' + name, body })
402
423
  }
403
424
 
404
- /** 文件内容页 *//** 文件内容页 */
405
- export function renderFile({ info, message, isError }) {
425
+ /** 文件内容页(text=源码;rendered=Markdown 渲染结果) */
426
+ export function renderFile({ info, message, isError, rendered = null }) {
427
+ const isMarkdown = /\.(?:md|markdown|mdown|mkd)$/iu.test(info.path)
428
+ const sourceHref = '/files/view?path=' + encodeURIComponent(info.path) + '&raw=1'
429
+ const renderedHref = '/files/view?path=' + encodeURIComponent(info.path)
430
+ const toggle = rendered
431
+ ? `<div class="chips"><a class="chip" href="${sourceHref}">查看源码</a></div>`
432
+ : (isMarkdown && info.error === undefined
433
+ ? `<div class="chips"><a class="chip" href="${renderedHref}">渲染 Markdown</a></div>`
434
+ : '')
406
435
  const body = `
407
436
  <div class="bar">
408
437
  <h1>${escapeHtml(info.path.split(/[\\/]/u).pop() ?? info.path)}</h1>
409
438
  <div class="path">${escapeHtml(info.path)}</div>
439
+ ${toggle}
410
440
  </div>
411
441
  ${messageHtml(message, isError)}
412
442
  ${info.error ? `<div class="msg err">${escapeHtml(info.error)}</div>` : ''}
413
- ${info.text !== undefined ? `<pre>${escapeHtml(info.text)}</pre>` : ''}
443
+ ${rendered ? `<article class="md-body">${rendered.html}</article>` : (info.text !== undefined ? `<pre>${escapeHtml(info.text)}</pre>` : '')}
414
444
  <div class="row">
415
445
  <a class="btn ghost" href="/files?path=${encodeURIComponent(info.path.replace(/[\\/][^\\/]*$/u, '') || '/')}"
416
446
  style="flex:1;text-align:center;padding:10px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;font-size:14px">返回目录</a>
@@ -478,10 +508,6 @@ export function renderGitPage({ repoPath, summary = null, args = '', result = nu
478
508
  style="flex:1;text-align:center;padding:10px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;font-size:14px">刷新</a>
479
509
  <a class="btn ghost" href="/files?path=${encodeURIComponent(repoPath)}"
480
510
  style="flex:1;text-align:center;padding:10px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;font-size:14px">看文件</a>
481
- <a class="btn ghost" href="/term"
482
- style="flex:1;text-align:center;padding:10px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;font-size:14px">终端</a>
483
- <a class="btn ghost" href="/"
484
- style="flex:1;text-align:center;padding:10px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;font-size:14px">DSH</a>
485
511
  </div>
486
512
  </div>
487
513
  ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
@@ -528,7 +554,7 @@ export function renderGitPage({ repoPath, summary = null, args = '', result = nu
528
554
  <pre>${escapeHtml(result.output ?? '')}</pre>
529
555
  `}
530
556
  <p class="crumbs">命令只执行 git 本身,不经过 shell;push/pull 用你本机已配置的凭据。</p>`
531
- return layout({ title: 'Git', body })
557
+ return layout({ title: 'Git', body, current: '/git' })
532
558
  }
533
559
 
534
560
  /** 编辑页:textarea + 保存 */
@@ -0,0 +1,384 @@
1
+ /**
2
+ * 轻量 Markdown 渲染器(零依赖、服务端渲染)。
3
+ *
4
+ * 目标:在手机 DSH 文件页里直接阅读 .md 文档。
5
+ *
6
+ * 安全原则:
7
+ * - 原始 HTML 一律转义,不直接输出(防止 markdown 文件注入脚本)
8
+ * - 链接/图片 URL 只允许 http(s)、mailto、tel、锚点、站内相对路径
9
+ * - javascript:/data:/vbscript:/file: 等协议直接拒绝
10
+ *
11
+ * 支持:标题、段落、列表(含嵌套/任务列表)、引用、代码块、行内代码、
12
+ * 粗体/斜体/删除线、链接、图片、表格、分隔线、自动链接。
13
+ */
14
+
15
+ const ESCAPE_MAP = {
16
+ '&': '&amp;',
17
+ '<': '&lt;',
18
+ '>': '&gt;',
19
+ '"': '&quot;',
20
+ "'": '&#39;',
21
+ }
22
+
23
+ export function escapeHtml(value) {
24
+ return String(value ?? '').replace(/[&<>"']/gu, (char) => ESCAPE_MAP[char])
25
+ }
26
+
27
+ const DANGEROUS_PROTOCOL = /^\s*(?:javascript|data|vbscript|file|blob)\s*:/iu
28
+
29
+ function cleanUrl(raw) {
30
+ let url = String(raw ?? '').trim()
31
+ if (url.startsWith('<') && url.endsWith('>')) url = url.slice(1, -1).trim()
32
+ if (url === '') return null
33
+ if (DANGEROUS_PROTOCOL.test(url)) return null
34
+ return url
35
+ }
36
+
37
+ function isExternal(url) {
38
+ return /^[a-z][a-z0-9+.-]*:/iu.test(url)
39
+ }
40
+
41
+ function splitUrl(url) {
42
+ const hashIndex = url.indexOf('#')
43
+ const hash = hashIndex >= 0 ? url.slice(hashIndex) : ''
44
+ let pathPart = hashIndex >= 0 ? url.slice(0, hashIndex) : url
45
+ const queryIndex = pathPart.indexOf('?')
46
+ const query = queryIndex >= 0 ? pathPart.slice(queryIndex) : ''
47
+ if (queryIndex >= 0) pathPart = pathPart.slice(0, queryIndex)
48
+ return { path: pathPart, query, hash }
49
+ }
50
+
51
+ /**
52
+ * 解析站内相对路径(图片/文件链接)。
53
+ * @returns {{kind:'external',url:string}|{kind:'file',path:string}|null}
54
+ */
55
+ function resolveTarget(raw, options) {
56
+ const url = cleanUrl(raw)
57
+ if (url === null) return null
58
+ if (url.startsWith('#')) return { kind: 'anchor', url }
59
+ if (isExternal(url)) {
60
+ if (/^https?:/iu.test(url)) return { kind: 'external', url }
61
+ if (/^(?:mailto|tel):/iu.test(url)) return { kind: 'external', url }
62
+ return null
63
+ }
64
+ const { path: pathPart, query, hash } = splitUrl(url)
65
+ if (pathPart === '') return { kind: 'anchor', url: '#' + hash.replace(/^#/u, '') }
66
+ let decoded = pathPart
67
+ try { decoded = decodeURIComponent(pathPart) } catch { /* 保持原样 */ }
68
+ if (decoded.includes('\0')) return null
69
+ const resolved = options.resolvePath ? options.resolvePath(decoded) : decoded
70
+ if (!resolved) return null
71
+ const suffix = query + hash
72
+ return { kind: 'file', path: resolved, suffix }
73
+ }
74
+
75
+ function inline(text, options) {
76
+ const stash = []
77
+ const put = (html) => {
78
+ const token = '\u0000' + stash.length + '\u0000'
79
+ stash.push(html)
80
+ return token
81
+ }
82
+
83
+ let out = String(text ?? '')
84
+
85
+ // 1) 行内代码 `code`
86
+ out = out.replace(/(`+)([^`]+?)\1/gu, (match, ticks, code) => put('<code>' + escapeHtml(code.trim()) + '</code>'))
87
+
88
+ // 2) 自动链接 <https://...>
89
+ out = out.replace(/<((?:https?|mailto):[^<>\s]+)>/giu, (match, url) => {
90
+ const target = resolveTarget(url, options)
91
+ if (target === null) return escapeHtml(match)
92
+ return put('<a href="' + escapeHtml(url) + '" target="_blank" rel="noopener noreferrer">' + escapeHtml(url) + '</a>')
93
+ })
94
+
95
+ // 3) 图片 ![alt](url "title")
96
+ out = out.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/gu, (match, alt, url) => {
97
+ const target = resolveTarget(url, options)
98
+ if (target === null) return escapeHtml(match)
99
+ const altText = escapeHtml(alt || '图片')
100
+ if (target.kind === 'external') {
101
+ // CSP 只允许站内图片:外链图片降级为链接,避免破图
102
+ return put('<a href="' + escapeHtml(target.url) + '" target="_blank" rel="noopener noreferrer">' + altText + '</a>')
103
+ }
104
+ if (target.kind !== 'file') return escapeHtml(match)
105
+ const src = options.imageHref ? options.imageHref(target.path) : target.path
106
+ if (!src) return escapeHtml(match)
107
+ return put('<a class="md-img" href="' + escapeHtml(src) + '" target="_blank" rel="noopener noreferrer"><img src="' + escapeHtml(src) + '" alt="' + altText + '" loading="lazy"></a>')
108
+ })
109
+
110
+ // 4) 链接 [text](url "title")
111
+ out = out.replace(/\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/gu, (match, label, url) => {
112
+ const target = resolveTarget(url, options)
113
+ if (target === null) return escapeHtml(match)
114
+ const text = inlineInline(label, options)
115
+ if (target.kind === 'anchor') {
116
+ return put('<a href="' + escapeHtml(target.url) + '">' + text + '</a>')
117
+ }
118
+ if (target.kind === 'external') {
119
+ return put('<a href="' + escapeHtml(target.url) + '" target="_blank" rel="noopener noreferrer">' + text + '</a>')
120
+ }
121
+ const href = options.fileHref ? options.fileHref(target.path, target.suffix) : target.path + target.suffix
122
+ if (!href) return escapeHtml(match)
123
+ return put('<a href="' + escapeHtml(href) + '">' + text + '</a>')
124
+ })
125
+
126
+ // 5) 转义剩余 HTML
127
+ out = escapeHtml(out)
128
+
129
+ // 6) 反斜杠转义:先占位成字面字符,避免后续强调语法误伤
130
+ out = out.replace(/\\([\\`*_{}\[\]()#+\-.!|>~])/gu, (match, char) => put(escapeHtml(char)))
131
+
132
+ // 7) 粗体 / 斜体 / 删除线
133
+ out = out.replace(/\*\*([^*]+)\*\*/gu, '<strong>$1</strong>')
134
+ out = out.replace(/__([^_]+)__/gu, '<strong>$1</strong>')
135
+ out = out.replace(/(^|[^*])\*([^*\s][^*]*?)\*/gu, '$1<em>$2</em>')
136
+ out = out.replace(/(^|[^_])_([^_\s][^_]*?)_(?!_)/gu, '$1<em>$2</em>')
137
+ out = out.replace(/~~([^~]+)~~/gu, '<del>$1</del>')
138
+
139
+ // 8) 恢复占位符
140
+ out = out.replace(/\u0000(\d+)\u0000/gu, (match, index) => stash[Number(index)] ?? '')
141
+ return out
142
+ }
143
+
144
+ function inlineInline(text, options) {
145
+ return inline(text, options)
146
+ }
147
+
148
+ function isBlank(line) {
149
+ return /^\s*$/u.test(line)
150
+ }
151
+
152
+ function matchFence(line) {
153
+ const match = /^\s{0,3}(`{3,}|~{3,})\s*([\w+-]*)\s*$/u.exec(line)
154
+ return match ? { marker: match[1][0], length: match[1].length, lang: match[2] || '' } : null
155
+ }
156
+
157
+ function matchHeading(line) {
158
+ const match = /^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/u.exec(line)
159
+ return match ? { level: match[1].length, text: match[2] } : null
160
+ }
161
+
162
+ function matchHr(line) {
163
+ return /^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/u.test(line)
164
+ }
165
+
166
+ function matchQuote(line) {
167
+ return /^\s{0,3}>\s?(.*)$/u.exec(line)
168
+ }
169
+
170
+ function matchListItem(line) {
171
+ const unordered = /^(\s*)([-*+])\s+(.*)$/u.exec(line)
172
+ if (unordered) return { indent: unordered[1].replace(/\t/gu, ' ').length, ordered: false, text: unordered[3] }
173
+ const ordered = /^(\s*)(\d{1,9})[.)]\s+(.*)$/u.exec(line)
174
+ if (ordered) return { indent: ordered[1].replace(/\t/gu, ' ').length, ordered: true, text: ordered[3] }
175
+ return null
176
+ }
177
+
178
+ function isTableSeparator(line) {
179
+ return /^\s*\|?\s*:?-{2,}:?\s*(?:\|\s*:?-{2,}:?\s*)+\|?\s*$/u.test(line)
180
+ }
181
+
182
+ function splitTableRow(line) {
183
+ let text = line.trim()
184
+ if (text.startsWith('|')) text = text.slice(1)
185
+ if (text.endsWith('|')) text = text.slice(0, -1)
186
+ return text.split('|').map((cell) => cell.trim().replace(/\\\|/gu, '|'))
187
+ }
188
+
189
+ function renderList(lines, start, options) {
190
+ const first = matchListItem(lines[start])
191
+ const baseIndent = first.indent
192
+ const baseOrdered = first.ordered
193
+ const items = []
194
+ let i = start
195
+
196
+ while (i < lines.length) {
197
+ const item = matchListItem(lines[i])
198
+ if (item === null) break
199
+ if (item.indent < baseIndent) break
200
+ if (item.ordered !== baseOrdered) break
201
+ if (item.indent > baseIndent) break // 同级里出现更深缩进:交给上一层的子列表处理
202
+
203
+ let text = item.text
204
+ let nested = ''
205
+ let j = i + 1
206
+ while (j < lines.length) {
207
+ if (isBlank(lines[j])) {
208
+ let k = j + 1
209
+ while (k < lines.length && isBlank(lines[k])) k += 1
210
+ if (k >= lines.length) { j = k; break }
211
+ const after = matchListItem(lines[k])
212
+ if (after === null) { j = k; break }
213
+ if (after.indent > item.indent + 1) {
214
+ const sub = renderList(lines, k, options)
215
+ nested += sub.html
216
+ j = sub.next
217
+ continue
218
+ }
219
+ if (after.indent <= item.indent) break
220
+ j = k
221
+ continue
222
+ }
223
+ const next = matchListItem(lines[j])
224
+ if (next !== null) {
225
+ if (next.indent > item.indent + 1) {
226
+ const sub = renderList(lines, j, options)
227
+ nested += sub.html
228
+ j = sub.next
229
+ continue
230
+ }
231
+ if (next.indent <= item.indent) break
232
+ // 同层新项
233
+ break
234
+ }
235
+ if (/^\s{2,}\S/u.test(lines[j])) {
236
+ text += '\n' + lines[j].trim()
237
+ j += 1
238
+ continue
239
+ }
240
+ break
241
+ }
242
+ items.push({ text, nested })
243
+ i = j
244
+ }
245
+
246
+ const tag = baseOrdered ? 'ol' : 'ul'
247
+ const html = items.map((item) => {
248
+ let content = item.text
249
+ let checkbox = ''
250
+ const task = /^\[([ xX])\]\s+(.*)$/u.exec(content)
251
+ if (task !== null) {
252
+ checkbox = '<input type="checkbox" disabled' + (task[1].toLowerCase() === 'x' ? ' checked' : '') + '> '
253
+ content = task[2]
254
+ }
255
+ return '<li>' + checkbox + inline(content, options) + item.nested + '</li>'
256
+ }).join('')
257
+ return { html: '<' + tag + '>' + html + '</' + tag + '>', next: i }
258
+ }
259
+
260
+ function renderTable(lines, start, options) {
261
+ const header = splitTableRow(lines[start])
262
+ const rows = []
263
+ let i = start + 2
264
+ while (i < lines.length && /\|/u.test(lines[i]) && !isBlank(lines[i])) {
265
+ rows.push(splitTableRow(lines[i]))
266
+ i += 1
267
+ }
268
+ const head = header.map((cell) => '<th>' + inline(cell, options) + '</th>').join('')
269
+ const body = rows.map((row) => {
270
+ const cells = header.map((_, index) => '<td>' + inline(row[index] ?? '', options) + '</td>').join('')
271
+ return '<tr>' + cells + '</tr>'
272
+ }).join('')
273
+ return { html: '<table><thead><tr>' + head + '</tr></thead><tbody>' + body + '</tbody></table>', next: i }
274
+ }
275
+
276
+ function startsBlock(line) {
277
+ return matchFence(line) !== null
278
+ || matchHeading(line) !== null
279
+ || matchHr(line)
280
+ || matchQuote(line) !== null
281
+ || matchListItem(line) !== null
282
+ || /^\s{0,3}(?:`{3,}|~{3,})/u.test(line)
283
+ }
284
+
285
+ /**
286
+ * 渲染 Markdown。
287
+ *
288
+ * @param {string} text
289
+ * @param {object} [options]
290
+ * @param {(relativePath: string) => string|null} [options.resolvePath] 相对路径 → 绝对路径
291
+ * @param {(absPath: string) => string|null} [options.imageHref] 图片 → 站内 URL
292
+ * @param {(absPath: string, suffix?: string) => string|null} [options.fileHref] 文件链接 → 站内 URL
293
+ * @returns {{html: string}}
294
+ */
295
+ export function renderMarkdown(text, options = {}) {
296
+ const lines = String(text ?? '').replace(/\r\n?/gu, '\n').split('\n')
297
+ const out = []
298
+ let i = 0
299
+
300
+ while (i < lines.length) {
301
+ const line = lines[i]
302
+ if (isBlank(line)) { i += 1; continue }
303
+
304
+ // 代码块
305
+ const fence = matchFence(line)
306
+ if (fence !== null) {
307
+ i += 1
308
+ const code = []
309
+ while (i < lines.length) {
310
+ const closing = matchFence(lines[i])
311
+ if (closing !== null && closing.marker === fence.marker && closing.length >= fence.length) { i += 1; break }
312
+ code.push(lines[i])
313
+ i += 1
314
+ }
315
+ const langClass = fence.lang ? ' class="language-' + escapeHtml(fence.lang) + '"' : ''
316
+ out.push('<pre><code' + langClass + '>' + escapeHtml(code.join('\n')) + '</code></pre>')
317
+ continue
318
+ }
319
+
320
+ // 标题
321
+ const heading = matchHeading(line)
322
+ if (heading !== null) {
323
+ const tag = 'h' + Math.min(6, Math.max(1, heading.level))
324
+ out.push('<' + tag + '>' + inline(heading.text, options) + '</' + tag + '>')
325
+ i += 1
326
+ continue
327
+ }
328
+
329
+ // 分隔线
330
+ if (matchHr(line)) { out.push('<hr>'); i += 1; continue }
331
+
332
+ // 引用(递归渲染内容)
333
+ const quote = matchQuote(line)
334
+ if (quote !== null) {
335
+ const quoted = []
336
+ while (i < lines.length) {
337
+ const current = matchQuote(lines[i])
338
+ if (current === null) break
339
+ quoted.push(current[1])
340
+ i += 1
341
+ }
342
+ out.push('<blockquote>' + renderMarkdown(quoted.join('\n'), options).html + '</blockquote>')
343
+ continue
344
+ }
345
+
346
+ // 表格
347
+ if (/\|/u.test(line) && i + 1 < lines.length && isTableSeparator(lines[i + 1])) {
348
+ const table = renderTable(lines, i, options)
349
+ out.push(table.html)
350
+ i = table.next
351
+ continue
352
+ }
353
+
354
+ // 列表
355
+ if (matchListItem(line) !== null) {
356
+ const list = renderList(lines, i, options)
357
+ out.push(list.html)
358
+ i = list.next
359
+ continue
360
+ }
361
+
362
+ // 段落:连续非空行(遇到其他块级语法停止)
363
+ const paragraph = [line]
364
+ i += 1
365
+ while (i < lines.length && !isBlank(lines[i])) {
366
+ const current = lines[i]
367
+ if (i + 1 < lines.length && isTableSeparator(lines[i + 1])) break
368
+ if (startsBlock(current) && paragraph.length > 0 && !/^\s{2,}/u.test(current)) break
369
+ paragraph.push(current)
370
+ i += 1
371
+ }
372
+ let html = inline(paragraph.join('\n'), options)
373
+ // 段内换行:行尾两个空格 / 反斜杠 → <br>
374
+ html = html.replace(/ {2,}\n/gu, '<br>\n').replace(/\\\n/gu, '<br>\n').replace(/\n/gu, ' ')
375
+ out.push('<p>' + html.trim() + '</p>')
376
+ }
377
+
378
+ return { html: out.join('\n') }
379
+ }
380
+
381
+ /** 是否看起来像 Markdown 文档(按扩展名判断) */
382
+ export function isMarkdownFile(filePath) {
383
+ return /\.(?:md|markdown|mdown|mkd|mdx?)$/iu.test(String(filePath ?? ''))
384
+ }
package/lib/nav.mjs ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * 插件内所有页面共用的顶部导航。
3
+ *
4
+ * 目标:无论从哪个页面(文件 / Git / 终端 / 窗口 / 桌面 / 调试 / 账户 / 登录…)
5
+ * 都能一眼看到并一键回到 DSH 主页。
6
+ */
7
+
8
+ export const NAV_CSS = `
9
+ .dsh-topnav { display:flex; gap:6px; overflow-x:auto; white-space:nowrap; align-items:center;
10
+ padding:8px 10px; margin:0 0 10px; background:#141920; border-bottom:1px solid #262b35;
11
+ position:sticky; top:0; z-index:30; -webkit-overflow-scrolling:touch; }
12
+ .dsh-topnav::-webkit-scrollbar { display:none; }
13
+ .dsh-topnav a { flex:0 0 auto; padding:7px 11px; border-radius:8px; background:#222833;
14
+ border:1px solid #333c48; color:#c7cdd8; text-decoration:none; font-size:13px; line-height:1.2; }
15
+ .dsh-topnav a:hover { background:#2c3442; }
16
+ .dsh-topnav a.home { background:#2f4b8f; border-color:#3f63b8; color:#fff; font-weight:600; }
17
+ .dsh-topnav .spacer { flex:1 1 auto; }
18
+ `
19
+
20
+ const LINKS = [
21
+ ['/', '← 返回 DSH', 'home'],
22
+ ['/files', '文件', ''],
23
+ ['/git', 'Git', ''],
24
+ ['/term', '终端', ''],
25
+ ['/remote', '窗口', ''],
26
+ ['/vnc', '桌面', ''],
27
+ ['/debug', '调试', ''],
28
+ ['/dsh_homing/account', '账户', ''],
29
+ ]
30
+
31
+ /**
32
+ * 顶部导航 HTML。
33
+ * @param {{ current?: string }} [options] current 可选:/files 等,用于高亮
34
+ */
35
+ export function topNav({ current = '' } = {}) {
36
+ const items = LINKS.map(([href, label, cls]) => {
37
+ const active = current !== '' && href === current
38
+ const classes = [cls, active ? 'active' : ''].filter(Boolean).join(' ')
39
+ const style = active ? ' style="background:#3a4658;color:#fff"' : ''
40
+ return '<a class="' + classes + '" href="' + href + '"' + style + '>' + label + '</a>'
41
+ }).join('')
42
+ return '<nav class="dsh-topnav">' + items + '</nav>'
43
+ }
package/lib/term-page.mjs CHANGED
@@ -8,6 +8,8 @@
8
8
  * 为了满足 CSP(不引外网脚本),xterm.js / xterm.css 都从本地 /term/vendor/ 提供,
9
9
  * 页面自身的脚本也从 /term/app.js 单独加载(不在 HTML 里内联)。
10
10
  */
11
+ import { NAV_CSS, topNav } from './nav.mjs'
12
+
11
13
  const escapeHtml = (value) => String(value ?? '')
12
14
  .replaceAll('&', '&amp;')
13
15
  .replaceAll('<', '&lt;')
@@ -83,15 +85,11 @@ export function renderTermPage({ cwd = '', host = '', user = '', connected = tru
83
85
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
84
86
  <title>终端 · DSH</title>
85
87
  <link rel="stylesheet" href="/term/vendor/xterm.css">
86
- <style>${STYLE}</style>
88
+ <style>${STYLE}${NAV_CSS}</style>
87
89
  </head>
88
90
  <body>
91
+ ${topNav({ current: '/term' })}
89
92
  <div class="bar">
90
- <a href="/">DSH</a>
91
- <a href="/files?path=${encodeURIComponent(cwd)}">文件</a>
92
- <a href="/git?path=${encodeURIComponent(cwd)}">Git</a>
93
- <a href="/remote">窗口</a>
94
- <a href="/vnc">桌面</a>
95
93
  ${shells.length > 0 ? `<form method="post" action="/term/shell" class="shellpick" style="display:flex;gap:4px;align-items:center;margin:0">
96
94
  <select name="shell" aria-label="终端类型" style="max-width:130px;padding:2px 4px;border-radius:5px;border:1px solid #333;background:#232323;color:#cfcfcf;font:inherit;font-size:11px">
97
95
  ${shellOptions}
package/lib/vnc-page.mjs CHANGED
@@ -4,6 +4,8 @@
4
4
  * 页面本身很薄,真正的协议在 /vnc/static/core/rfb.js 里;
5
5
  * 连接地址固定为同源的 /vnc/ws(由插件代理到本机 VNC 服务端)。
6
6
  */
7
+ import { NAV_CSS, topNav } from './nav.mjs'
8
+
7
9
  const escapeHtml = (value) => String(value ?? '')
8
10
  .replaceAll('&', '&amp;')
9
11
  .replaceAll('<', '&lt;')
@@ -53,14 +55,11 @@ export function renderVncPage({ host = '', user = '', target = '127.0.0.1:5900',
53
55
  <meta charset="utf-8">
54
56
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
55
57
  <title>桌面 · DSH</title>
56
- <style>${STYLE}</style>
58
+ <style>${STYLE}${NAV_CSS}</style>
57
59
  </head>
58
60
  <body>
61
+ ${topNav({ current: '/vnc' })}
59
62
  <div class="bar">
60
- <a href="/">DSH</a>
61
- <a href="/files">文件</a>
62
- <a href="/term">终端</a>
63
- <a href="/remote">窗口</a>
64
63
  <span class="spacer"></span>
65
64
  <span>${escapeHtml(user)}@${escapeHtml(host)}</span>
66
65
  <span id="status">${ready ? '未连接' : 'noVNC 资源缺失'}</span>
@@ -3,6 +3,8 @@
3
3
  *
4
4
  * 页面只负责渲染;抓图与输入由 /remote/frame、/remote/input 完成。
5
5
  */
6
+ import { NAV_CSS, topNav } from './nav.mjs'
7
+
6
8
  const escapeHtml = (value) => String(value ?? '')
7
9
  .replaceAll('&', '&amp;')
8
10
  .replaceAll('<', '&lt;')
@@ -71,14 +73,11 @@ export function renderWindowPage({ host = '', user = '', supported = true, agent
71
73
  <meta charset="utf-8">
72
74
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
73
75
  <title>窗口共享 · DSH</title>
74
- <style>${STYLE}</style>
76
+ <style>${STYLE}${NAV_CSS}</style>
75
77
  </head>
76
78
  <body>
79
+ ${topNav({ current: '/remote' })}
77
80
  <div class="bar">
78
- <a href="/">DSH</a>
79
- <a href="/files">文件</a>
80
- <a href="/term">终端</a>
81
- <a href="/vnc">桌面</a>
82
81
  <span class="spacer"></span>
83
82
  <span>${escapeHtml(user)}@${escapeHtml(host)}</span>
84
83
  <span id="status">${supported ? (agent ? '代理已启动' : '代理未启动') : '仅支持 Windows'}</span>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andy.ian/dsh-homing",
3
- "version": "2.1.13",
3
+ "version": "2.1.15",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [